<template>
  <div class="account-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        v-model="searchQuery"
        placeholder="请输入用户ID或用户名"
        style="width: 300px; margin-right: 10px"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
      <el-button 
        type="primary" 
        icon="el-icon-download"
        @click="exportToExcel"
        style="margin-left: 10px"
      >
        导出Excel
      </el-button>
    </div>

    <!-- 账号管理表格 -->
    <el-table :data="filteredAccounts" border style="width: 100%">
      <el-table-column prop="id" label="用户ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="status" label="账号状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lastLogin" label="最后登录时间" width="180"></el-table-column>
      <el-table-column prop="loginIp" label="最后登录IP" width="150"></el-table-column>
      <el-table-column prop="loginAttempts" label="失败尝试" width="100"></el-table-column>
      <el-table-column label="在线状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.onlineStatus === '在线' ? 'success' : 'info'">
            {{ scope.row.onlineStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="loginAttempts" label="操作" width="220">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            :type="scope.row.status === '正常' ? 'danger' : 'success'"
            @click="toggleAccountStatus(scope.row)"
          >
            {{ scope.row.status === '正常' ? '冻结' : '解冻' }}
          </el-button>
          <el-button 
            size="mini" 
            type="warning" 
            @click="showLoginHistory(scope.row)"
          >
            登录记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalAccounts"
    ></el-pagination>

    <!-- 登录记录对话框 -->
    <el-dialog title="登录记录" :visible.sync="loginHistoryVisible" width="70%">
      <el-table :data="loginHistoryData" border>
        <el-table-column prop="loginTime" label="登录时间" width="180"></el-table-column>
        <el-table-column prop="ip" label="IP地址" width="150"></el-table-column>
        <el-table-column prop="device" label="设备信息"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { exportJsonToExcel } from '@/utils/export2Excel'

export default {
  name: 'UserAccountManagement',
  data() {
    return {
      accounts: [
        {
          id: 101,
          username: '张三',
          status: '正常',
          lastLogin: '2023-05-15 14:30:22',
          loginIp: '192.168.1.100',
          loginAttempts: 0,
          // 新增在线状态数据
          onlineStatus: '在线'
        },
        {
          id: 102,
          username: '李四',
          status: '冻结',
          lastLogin: '2023-05-10 09:15:45',
          loginIp: '120.230.110.50',
          loginAttempts: 5,
          // 新增在线状态数据
          onlineStatus: '离线'
        },
        // 可以添加更多模拟数据
      ],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      loginHistoryVisible: false,
      loginHistoryData: []
    }
  },
  computed: {
    filteredAccounts() {
      return this.accounts.filter(account => {
        return (
          account.id.toString().includes(this.searchQuery) ||
          account.username.includes(this.searchQuery)
        )
      })
    },
    totalAccounts() {
      return this.filteredAccounts.length
    }
  },
  methods: {
    handleSearch() {
      // 搜索逻辑已在computed中实现
    },
    toggleAccountStatus(row) {
      const newStatus = row.status === '正常' ? '冻结' : '正常'
      this.$confirm(`确定要${newStatus === '冻结' ? '冻结' : '解冻'}该账号吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.status = newStatus
        if (newStatus === '冻结') {
          this.$message.warning(`已冻结账号 ${row.username}`)
        } else {
          this.$message.success(`已解冻账号 ${row.username}`)
        }
      })
    },
    showLoginHistory(row) {
      // 模拟登录历史数据
      this.loginHistoryData = [
        {
          loginTime: '2023-05-15 14:30:22',
          ip: '192.168.1.100',
          device: 'Windows 10 Chrome',
          status: '成功'
        },
        {
          loginTime: '2023-05-14 09:15:45',
          ip: '120.230.110.50',
          device: 'Android Mobile',
          status: '失败'
        },
        // 可以添加更多历史记录
      ]
      this.loginHistoryVisible = true
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleUserStatusChanged({ userId, status }) {
      const account = this.accounts.find(a => a.id === userId)
      if (account) {
        account.status = status
        this.$message.success(`账号 ${account.username} 状态已更新为 ${status}`)
      }
    },
    exportToExcel() {
      const tHeader = ['用户ID', '用户名', '账号状态', '最后登录时间', '最后登录IP', '失败尝试', '在线状态']
      const filterVal = ['id', 'username', 'status', 'lastLogin', 'loginIp', 'loginAttempts', 'onlineStatus']
      const data = this.filteredAccounts.map(account => filterVal.map(key => account[key]))
      
      exportJsonToExcel(tHeader, data, '用户账号列表')
    }
  },
  created() {
    // 监听评论管理组件发出的事件
    this.$on('user-status-changed', this.handleUserStatusChanged)
  },
  beforeDestroy() {
    // 组件销毁时移除事件监听
    this.$off('user-status-changed', this.handleUserStatusChanged)
  }
}
</script>

<style scoped>
.account-container {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>